import axios from 'axios';
import router from '../router/index.js'
import { OnionHandler } from './onion-handler';
import Cookies from 'js-cookie';


const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    timeout: 10000
});

/**
 * HTTP请求拦截器
 */
service.interceptors.request.use(
    config => {
        let xToken = Cookies.get("x-token");
        if(xToken && xToken!="" && xToken!=null){
            if(!config.headers){
                config.headers = {"x-token":xToken};
            }else{
                config.headers["x-token"] = xToken;
            }
        }
        if(config.headers && config.headers["Build-Type"]){
            let buildType = config.headers["Build-Type"];
            config.data = OnionHandler.buildData(config.data, buildType);
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

/**
 * HTTP响应拦截器
 */
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            let result = response.data;
            if(result && result.code==5000){
                router.push({path: '/login'});
                return result;
            }else{
                return response.data;
            }
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;
